package com.muxue.module.ai.config;

import com.muxue.common.config.security.TokenService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.ClientRequest;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;

@Service
public class SecurityContextWebClientFilter {

    @Autowired
    private TokenService tokenService;

    public ExchangeFilterFunction securityContextFilter(HttpServletRequest httpRequest) {
        String token = tokenService.getToken(httpRequest);
        return ExchangeFilterFunction.ofRequestProcessor(request ->
                ReactiveSecurityContextHolder.getContext()
                        .map(SecurityContext::getAuthentication)
                        .filter(auth -> auth != null && auth.isAuthenticated())
                        .map(auth -> addAuthHeader(request, token))
                        .defaultIfEmpty(request)
        );
    }

    private static ClientRequest addAuthHeader(ClientRequest request, String token) {

        return ClientRequest.from(request)
                .header("Authorization", "Bearer " + token)
                .build();
    }


}
